package com.tssup.fesco.search.dao;


import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Repository;

import javax.annotation.PreDestroy;
import java.net.InetAddress;

@Repository
public class ESClient {

    private Client client;

    private final Logger logger = LoggerFactory.getLogger(getClass());

    public ESClient(Environment env) {
        super();
        try {
            String ESHost = env.getProperty("elasticsearch.host");
            int ESPort = Integer.parseInt(env.getProperty("elasticsearch.port"));

            client = TransportClient.builder().build().addTransportAddress(
                            new InetSocketTransportAddress(InetAddress.getByName(ESHost), ESPort));
            logger.info("Initializing es client complete.");

        } catch (Exception e) {
            logger.error("Initializing es client fail: ", e);
        }
    }

    public Client getESClient() {
        return client;
    }

    @PreDestroy
    public void clientClose() {
        try {
            client.close();
            logger.info("ES client has been closed.........");
        } catch (Exception e) {
            logger.error("Closing ES get error: ", e);
        }
    }
}
